package org.example.network;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

public class FlyBookClient {

    public static void main(String[] args) throws IOException {
        FlyBookClient  flyBookClient = new FlyBookClient();
        flyBookClient.start();
    }

    private Scanner scanner = new Scanner(System.in);
    private String name;
    private Socket socket;

    public void start() throws IOException {
        socket = new Socket("localhost", 8888);
        System.out.print("请输入姓名:");
        name = scanner.nextLine();
        DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
        dataOutputStream.writeUTF(name);
        new Thread(this::recv).start();
        new Thread(this::send).start();
    }

    public void send(){
        try{
            DataOutputStream dataOutputStream =
                    new DataOutputStream(socket.getOutputStream());
            while(true){
                System.out.print("请输入类型:");
                String type = scanner.nextLine();
                dataOutputStream.writeUTF(type);
                System.out.print("请输入消息:");
                String msg = scanner.nextLine();
                dataOutputStream.writeUTF(msg);
            }
        }catch (Exception e){
            throw  new RuntimeException(e);
        }
    }

    public void recv(){
        try{
            DataInputStream  dataInputStream =
                    new DataInputStream(socket.getInputStream());
            while(true){
                String type = dataInputStream.readUTF();
                if("msg".equals(type)){
                    String msg = dataInputStream.readUTF();
                    System.out.println(msg);
                }
            }
        } catch (Exception e){
            throw new RuntimeException(e);
        }

    }
}
